﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MoneyWentWhere.Utils;
using System.Runtime.Serialization;

namespace MoneyWentWhere.DataModel
{
    /// <summary>
    /// Set of tags, ordered alphabetically.
    /// </summary>
    [DataContract]
    public class TagSet : IEnumerable<String>
    {
        [DataMember]
        List<String> _tags;

        public TagSet(IEnumerable<string> tags = null)
        {
            if (tags != null)
            {
                tags.ForEach(t => Add(t));
            }
        }

        List<String> Tags
        {
            get { return Lazy.Get(ref _tags, () => new List<String>()); }
        }

        public void Add(String newTag)
        {
            if (Tags.Contains(newTag)) { return; }

            // Keep sorted
            int index = 0;
            while (index < Tags.Count && Tags[index].CompareTo(newTag) < 0) { index++; }
            Tags.Insert(index, newTag);
        }

        public void ReplaceAll(IEnumerable<String> tags)
        {
            Clear();
            tags.ForEach(t => Add(t));
        }

        public void Remove(String tag)
        {
            if (Tags.Contains(tag)) { return; }

            Tags.Remove(tag);
        }

        public void Clear()
        {
            Tags.Clear();
        }

        public bool Contains(String tag)
        {
            return Tags.Contains(tag);
        }

        public IEnumerator<string> GetEnumerator()
        {
            return Tags.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public override string ToString()
        {
            return "Tags:" + String.Join(" ", Tags);
        }
    }

}
